<template>
  <div class="adminPage">
    <!-- 搜索框 -->
    <div class="search_area">
      <el-form
        :model="params"
        label-width="80px"
        style="display: flex; margin-bottom: 50px"
      >
        <el-form-item label="分类名称">
          <el-input
            clearable
            placeholder="请输入分类名称"
            v-model="params.name"
            style="width: 200px"
            prefix-icon="el-icon-search"
          />
        </el-form-item>
        <el-form-item label="分类描述">
          <el-input
            clearable
            placeholder="请输入分类描述"
            v-model="params.description"
            style="width: 200px"
            prefix-icon="el-icon-search"
          />
        </el-form-item>
        <el-form-item>
          <div class="search-buttons">
            <el-button type="warning" style="margin-left: 10px" @click="search"
              >查询</el-button
            >
            <el-button type="primary" style="margin-left: 10px" @click="addUser"
              v-if="$store.state.userInfo.role !== 'ROLE_STUDENT'"
              >新增</el-button
            >
            <!--对于批量删除的删除按钮，需要判断当前选中的行数是否大于0，该逻辑需要写到外层，否则提示框不会出现  -->
            <el-popconfirm
              title="确定批量删除吗？"
              @confirm="delBatBookType"
              v-if="multipleSelection.length > 0 && $store.state.userInfo.role !== 'ROLE_STUDENT'"
            >
              <el-button slot="reference" type="warning">批量删除</el-button>
            </el-popconfirm>
            <el-button
              type="success"
              style="margin-left: 10px"
              @click="exportBookType"
              >批量导出</el-button
            >
            <!-- 这个地方如果可以添加请求的后端地址-->
            <el-upload
              action="http://localhost:8888/api/bookTypes/import"
              :on-success="successUpload"
              style="display: inline-block"
              :show-file-list="false"
            >
              <el-button type="primary">批量导入</el-button>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>
    </div>

    <!--表单数据-->
    <div>
      <!-- <el-table
        :data="tableData"
        style="width: 100%"
        :header-cell-style="{
          background: '#fafafa',
          color: '#262626',
          fontSize: '14px',
          fontWeight: '500',
          height: '10px',
        }"
      >
        <el-table-column prop="name" label="分类名称"> </el-table-column>
        <el-table-column prop="description" label="分类描述"> </el-table-column>
        <el-table-column fixed="right" label="操作">
          <template slot-scope="scope">
            <el-button type="primary" @click="updBookType(scope.row)"
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除吗？"
              @confirm="delBookType(scope.row)"
            >
              <el-button slot="reference" type="warning">删除</el-button>
            </el-popconfirm>
          </template>
</el-table-column>
</el-table> -->
      <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        @selection-change="handleSelectionChange"
        :row-key="getRowKeys"
        style=""
      >
        <!-- reserve-selection="true"配合row-key="getRowKeys" 可以实现跨页记录选中-->
        <el-table-column type="selection" width="55" :reserve-selection="true">
        </el-table-column>
        <el-table-column prop="name" label="分类名称"> </el-table-column>
        <el-table-column prop="description" label="分类描述"> </el-table-column>
        <el-table-column label="操作" v-if="$store.state.userInfo.role !== 'ROLE_STUDENT'" >
          <template slot-scope="scope">
            <el-button type="primary" @click="updBookType(scope.row)" 
              >编辑</el-button
            >
            <el-popconfirm
              title="确定删除吗？"
              @confirm="delBookType(scope.row)"
            >
              <el-button slot="reference" type="warning">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="block" style="margin-top: 20px">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pageNo"
        :page-sizes="[1, 5, 10, 20]"
        :page-size="params.pageSize"
        layout="total, sizes, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 新增分类、编辑分类弹窗 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="currentData" label-width="80px">
        <el-form-item label="分类名称" :label-width="formLabelWidth">
          <el-input v-model="currentData.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="分类描述" :label-width="formLabelWidth">
          <el-input
            v-model="currentData.description"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addBookType,
  deleteBookType,
  updateBookType,
  getAllBookTypes,
  delBatchBookType,
} from "../../../api/sys/bookType";

export default {
  name: "BookType",
  data() {
    return {
      //分页查询参数
      params: {
        pageSize: 10,
        pageNo: 1,
        name: "",
        description: "",
      },
      dialogFormVisible: false, //对话框是否可见
      tableData: [], //表单数据
      loading: "", //加载状态
      total: "", //数据条数
      isEdit: false, //是否是编辑状态
      title: "", //对话框标题
      currentData: {}, //当前行数据
      multipleSelection: [], //多选数据
    };
  },
  created() {
    this.loadData();
  },
  methods: {
    //加载分类信息
    async loadData() {
      this.loading = true;
      try {
        const res = await getAllBookTypes(this.params);
        if (res.code === 200) {
          this.tableData = res.data.list || [];
          this.total = res.data.total || 0;
        } else if (res.code === 10001) {
          this.$message.error(res.message);
          //清理登录信息
          this.$store.dispatch("Logout");
        }
      } finally {
        this.loading = false;
      }
    },
    //根据输入模糊查询
    search() {
      this.params.pageNo = 1;
      this.loadData();
    },
    //页码尺寸变化
    handleSizeChange(pageSize) {
      this.params.pageSize = pageSize;
      this.params.pageNo = 1;
      this.loadData();
    },
    //当前页变化
    handleCurrentChange(pageNo) {
      this.params.pageNo = pageNo;
      this.loadData();
    },
    //新增分类
    addUser() {
      this.currentData = {};
      this.isEdit = false;
      this.dialogFormVisible = true;
      this.title = "新增分类";
    },

    async submitDialog() {
      const data = this.currentData;
      const res = this.isEdit
        ? await updateBookType(data)
        : await addBookType(data); //注意：没有await拿不到res数据
      console.log(res);
      if (res.code === 200) {
        this.$message.success("操作成功");
        this.dialogFormVisible = false;
        this.loadData();
      }
    },

    //删除分类
    delBookType(data) {
      this.$confirm("此操作将永久删除该分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          const id = data.id;
          deleteBookType(id).then((res) => {
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.loadData();
            }
          });
        })
        .catch(() => {
          this.$message.error("取消删除成功");
        });
    },
    //修改分类
    updBookType(data) {
      this.isEdit = true;
      this.dialogFormVisible = true;
      this.title = "修改分类";
      this.currentData = data; //当前行数据
    },
    //批量选中
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(this.multipleSelection);
    },
    //批量删除
    delBatBookType() {
      console.log(this.multipleSelection);
      this.$confirm("此操作将永久批量删除分类, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delBatchBookType(this.multipleSelection).then((res) => {
            if (res.code === 200) {
              this.$message.success("批量删除成功");
              this.loadData();
            }
          });
        })
        .catch(() => {
          this.$message.error("已取消批量删除");
          // 取消批量删除即恢复多选框的选中状态
          this.$refs.multipleTable.clearSelection();
        });
    },
    //记录选中行的id
    getRowKeys(row) {
      return row.id;
    },
    //导出报表
    exportBookType() {
      //导出报表
      //请求该接口的时候，后端接口会拦截接口，可以在后面拼接token
      // location.href = "http://localhost:8888/api/bookTypes/export？token=" + this.$store.state.token;";
      location.href = "http://localhost:8888/api/bookTypes/export";
    },
    //点击导入成功后的回调
    successUpload(res) {
      if (res.code === 200) {
        this.$message.success("导入成功");
        this.loadData();
      } else {
        this.$message.error("导入失败");
      }
    },
  },
};
</script>

<style>
.adminPage {
  min-height: 100%;
  background-color: transparent;
}

.el-button {
  margin: 5px;
}

.search_area {
  margin-top: 20px;
}
</style>